package com.example.demo;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/submit")
public class FormSubmitServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/personal_info_db?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        Map<String, Object> result = new HashMap<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            Map<String, String> formData = new HashMap<>();
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                String paramValue = request.getParameter(paramName);
                formData.put(paramName, paramValue);
            }
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            String sql = "INSERT INTO personal_information " +
                    "(full_name, gender, birthdate, id_number, phone, email, address) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, formData.get("fullName"));
            pstmt.setString(2, formData.get("gender").equals("male") ? "M" : "F");
            pstmt.setString(3, formData.get("birthdate"));
            pstmt.setString(4, formData.get("idNumber"));
            pstmt.setString(5, formData.get("phone"));
            pstmt.setString(6, formData.get("email"));
            pstmt.setString(7, formData.get("address"));
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                result.put("success", true);
                result.put("message", "注册成功");
                System.out.println("数据存储成功，ID: " + getLastInsertId(conn));
            } else {
                result.put("success", false);
                result.put("message", "注册失败：数据未插入");
            }

            response.setStatus(HttpServletResponse.SC_OK);
        } catch (SQLException e) {
            result.put("success", false);
            result.put("message", "注册失败：数据库错误 - " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            try {
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        try (PrintWriter out = response.getWriter()) {
            out.print(toJsonString(result));
        }
    }
    private long getLastInsertId(Connection conn) throws SQLException {
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT LAST_INSERT_ID()")) {
            if (rs.next()) {
                return rs.getLong(1);
            }
            return -1;
        }
    }
    private String toJsonString(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean firstEntry = true;

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!firstEntry) {
                json.append(",");
            }
            json.append("\"").append(entry.getKey()).append("\":");

            Object value = entry.getValue();
            if (value instanceof String) {
                json.append("\"").append(value).append("\"");
            } else {
                json.append(value);
            }

            firstEntry = false;
        }

        json.append("}");
        return json.toString();
    }
}